import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import apiRoutes from './routes';
import { mastra } from '../mastra/index';

/**
 * 赛博侦探游戏AI服务器
 * 提供案件生成、嫌疑人对话、推理判断等API接口
 */

const app = express();
const PORT = process.env.PORT || 3001;

/**
 * 中间件配置
 */

// 安全中间件
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      scriptSrc: ["'self'"],
      imgSrc: ["'self'", "data:", "https:"],
    },
  },
}));

// CORS配置 - 允许前端项目访问
app.use(cors({
  origin: [
    'http://localhost:5173', // Vite开发服务器
    'http://localhost:3000', // 备用端口
    'https://cyber-detective-game.vercel.app', // 生产环境域名
  ],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
}));

// 请求体解析
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 请求日志
app.use((req, res, next) => {
  const timestamp = new Date().toISOString();
  console.log(`[${timestamp}] ${req.method} ${req.path}`);
  
  // 记录请求体（排除敏感信息）
  if (req.method !== 'GET' && req.body) {
    const safeBody = { ...req.body };
    // 移除可能的敏感信息
    delete safeBody.password;
    delete safeBody.token;
    console.log('Request body:', JSON.stringify(safeBody, null, 2));
  }
  
  next();
});

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 每个IP最多100个请求
  message: {
    success: false,
    message: '请求过于频繁，请稍后再试',
    error: 'RATE_LIMIT_EXCEEDED'
  },
  standardHeaders: true,
  legacyHeaders: false,
});

app.use('/api', limiter);

/**
 * 路由配置
 */

// 根路径
app.get('/', (req, res) => {
  res.json({
    name: '赛博侦探游戏AI服务',
    version: '1.0.0',
    description: '基于Mastra AI框架的推理游戏后端服务',
    endpoints: {
      health: '/api/health',
      startGame: 'POST /api/game/start',
      chatSuspect: 'POST /api/game/chat',
      submitDeduction: 'POST /api/game/submit',
      getStatus: 'GET /api/game/status/:gameId',
      getCases: 'GET /api/game/cases',
      getStats: 'GET /api/game/stats/:gameId',
      resetGame: 'DELETE /api/game/reset/:gameId'
    },
    timestamp: new Date().toISOString()
  });
});

// API路由
app.use('/api', apiRoutes);

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
    error: 'NOT_FOUND',
    path: req.originalUrl
  });
});

// 全局错误处理
app.use((error: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error('服务器错误:', error);
  
  // 开发环境返回详细错误信息
  const isDevelopment = process.env.NODE_ENV === 'development';
  
  res.status(error.status || 500).json({
    success: false,
    message: '服务器内部错误',
    error: isDevelopment ? error.message : 'INTERNAL_SERVER_ERROR',
    ...(isDevelopment && { stack: error.stack })
  });
});

/**
 * 服务器启动
 */
async function startServer() {
  try {
    console.log('正在初始化Mastra AI框架...');
    
    // 确保Mastra实例已正确初始化
    if (!mastra) {
      throw new Error('Mastra实例初始化失败');
    }
    
    console.log('Mastra AI框架初始化成功');
    console.log('已注册的工作流:', Object.keys(mastra.workflows || {}));
    console.log('已注册的Agent:', Object.keys(mastra.agents || {}));
    
    // 启动HTTP服务器
    const server = app.listen(PORT, () => {
      console.log(`\n🚀 赛博侦探游戏AI服务已启动`);
      console.log(`📡 服务地址: http://localhost:${PORT}`);
      console.log(`🔍 健康检查: http://localhost:${PORT}/api/health`);
      console.log(`📚 API文档: http://localhost:${PORT}`);
      console.log(`⏰ 启动时间: ${new Date().toISOString()}\n`);
    });
    
    // 优雅关闭处理
    const gracefulShutdown = (signal: string) => {
      console.log(`\n收到${signal}信号，正在优雅关闭服务器...`);
      
      server.close((err) => {
        if (err) {
          console.error('关闭服务器时出错:', err);
          process.exit(1);
        }
        
        console.log('服务器已安全关闭');
        process.exit(0);
      });
      
      // 强制关闭超时
      setTimeout(() => {
        console.error('强制关闭服务器');
        process.exit(1);
      }, 10000);
    };
    
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));
    
    // 未捕获异常处理
    process.on('uncaughtException', (error) => {
      console.error('未捕获的异常:', error);
      process.exit(1);
    });
    
    process.on('unhandledRejection', (reason, promise) => {
      console.error('未处理的Promise拒绝:', reason);
      console.error('Promise:', promise);
      process.exit(1);
    });
    
  } catch (error) {
    console.error('启动服务器失败:', error);
    process.exit(1);
  }
}

// 如果直接运行此文件，则启动服务器
if (require.main === module) {
  startServer();
}

export default app;
export { startServer };